import requests


class SendMethod:
    @staticmethod
    def send_method(method, url, params=None, data=None, json=None, headers=None):
        """
        封装请求,获取对应的响应
        :param method: 请求方式
        :param url: 请求地址
        :param params: get请求参数
        :param data: post请求x-www-form-urlencoded格式的参数
        :param json: post请求JSON格式
        :return: 响应
        """
        if method == 'get':  # 当请求方式为get时
            response = requests.get(url=url, params=params, headers=headers)
        elif method == 'post':  # 当请求方式为post时
            if data is None and json is None:  # post 不带参数的请求
                response = requests.post(url=url, headers=headers)
            elif data is not None and json is None:  # 请求参数x-www-form-urlencoded
                response = requests.post(url=url, data=data, headers=headers)
            else:  # 请求参数为json格式
                response = requests.post(url=url, json=json, headers=headers)
        else:
            response = None
            print('请求方式错误')

        # 获取响应
        result = {}
        if response is not None:  # 判断response是否为空
            result['status_code'] = response.status_code  # 获取状态码
            result['body'] = response.json()  # 获取响应体
            result['headers'] = response.headers  # 获取响应头
            result['response_time'] = int(response.elapsed.microseconds / 1000)  # 获取响应时
            return result
        else:
            return response


if __name__ == '__main__':
    url = 'http://47.108.206.100:8080/admin/login'
    payload = {
        'username': 'admin',
        'password': 'macro123'
    }
    method = 'post'
    print(SendMethod.send_method(method=method, url=url, json=payload))